package cn.tradewin.advisor.validators;

import java.util.regex.Pattern;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.validator.AbstractValidator;

public class AlphanumericValidator extends AbstractValidator<Void, String> {

	private static final Pattern PATTERN = Pattern.compile("[a-zA-Z0-9]+");
	
	public AlphanumericValidator(JavaScriptSupport javaScriptSupport) {
		super(null, String.class, "invalid-alphanumeric", javaScriptSupport);
	}
	
	@Override
	public void validate(Field field, Void constraintValue,
			MessageFormatter formatter, String value)
			throws ValidationException {
		if (!PATTERN.matcher(value).matches()) throw new ValidationException(formatter.toString());	
	}

	@Override
	public void render(Field field, Void constraintValue,
			MessageFormatter formatter, MarkupWriter writer,
			FormSupport formSupport) {		
	}

}
